import Bus from "./bus";
import store from "./store";
import server_api from "./server_api";

class MessageQueue {
  queue: never[];
  id: Number;
  constructor() {
    this.queue = [];
    this.id = -1;
  }

  enqueue(message: any) {
    this.queue.push(message);
  }

  dequeue() {
    return this.queue.shift();
  }

  size() {
    return this.queue.length;
  }

  isEmpty() {
    return this.queue.length === 0;
  }
}

const connecting = ref(false);
const connect = ref(false);
const ws_client = ref<WebSocket>();
const messageQueue = ref(new MessageQueue());
const messageStreamQueue = ref(new MessageQueue());
const requestQueue = ref(new MessageQueue());
const config = ref(store);
const lastTime = ref(0);

Bus.on("push.msg", (v) => {
  requestQueue.value.enqueue(v);
});

let server_url = window.location.hostname;
let server_host = window.location.host;
if (import.meta.env.DEV || window.location.port.indexOf("41") !== -1) {
  server_host = "192.168.15.114";
  server_url = "192.168.15.114/v1/ws"; // 替换为你的 测试 WebSocket服务器地址
}
else server_url += "/v1/ws"; // 替换为你的 WebSocket服务器地址

function setupWebSocket() {
  if (window.socket)
    return; // 如果已经存在WebSocket连接，则直接返回
  let wsServer = "ws://" + server_url;
  var ws = new WebSocket(wsServer);
  connecting.value = true;
  lastTime.value = Date.now();

  function delete_ws() {
    ws_client.value = undefined;
    connecting.value = false;
    connect.value = false;
    if (window.socket) {
      let last_ws = window.socket;
      last_ws.onopen = null;
      last_ws.onclose = null;
      last_ws.onmessage = null;
      last_ws.onerror = null;
      // if (last_ws.readyState == WebSocket.OPEN) last_ws.close(); // 关闭旧的WebSocket连接
      delete window.socket;
    }
    delete ws_client.value; // 清除WebSocket对象
  }

  ws.onopen = function (evt) {
    console.log("Connected to WebSocket server.");
    delete_ws();
    ws_client.value = ws;
    window.socket = ws;
    connect.value = true;
    lastTime.value = Date.now();
    server_api.refresh_chip_info();
    server_api.refresh_wifi_info();
    server_api.refresh_afe_config();
    server_api.refresh_ota_config();
    server_api.refresh_logs();
    lastTime.value = Date.now();
  };

  ws.onclose = function (evt) {
    console.log("Disconnected");
    delete_ws();
    // 断线重连
    setTimeout(setupWebSocket, 1000); // 1秒后尝试重新连接
  };

  ws.onmessage = async function (evt) {
    lastTime.value = Date.now();
    const blobToString = (blobData) => {
      return new Promise((resolve) => {
        if (blobData instanceof Blob) {
          const reader = new FileReader();
          reader.readAsText(blobData, "utf-8");
          reader.onload = function () {
            resolve(reader.result || "");
          };
        } else {
          resolve(blobData);
        }
      });
    };
    let res = evt.data;
    // console.log("Received Message: ", res);
    if (evt.data instanceof Blob) res = await blobToString(evt.data);
    try {
      let data = JSON.parse(res);
      if (data?.api == "pong") return; // 心跳包
      console.log("Received Message: ", data);
      // 处理接收到的数据
      messageQueue.value.enqueue(data);
    } catch (err) {
      console.log("Received Message: ", res);
      // 处理接收到数据流
      messageStreamQueue.value.enqueue(evt.data);
    }
  };

  ws.onerror = function (evt) {
    // console.error("WebSocket Error: ", evt);
  };
}

setupWebSocket(); // 初始化WebSocket连接

/* 心跳判断 */
setInterval(() => {
  if (!connect.value) return;
  if (Date.now() - lastTime.value >= 90 * 1000) {
    ws_client.value?.send(JSON.stringify({ api: "ping" }));
    server_api.refresh_chip_info();
  }
}, 1 * 1000);

setInterval(() => {
  if (!connect.value) return;
  /* 60s 内没有通讯则断开连接 */
  if (Date.now() - lastTime.value > 60 * 1000) {
    if (ws_client.value) {
      ws_client.value?.close();
      connect.value = false;
    }
    return;
  }
  if (!requestQueue.value.isEmpty()) {
    const len = requestQueue.value.size();
    for (let i = 0; i < len; i++) {
      const message = requestQueue.value.dequeue();
      if (ws_client.value) {
        console.log(
          "send message: ",
          "api" in message,
          JSON.stringify(message),
          message
        );
        if ("api" in message) ws_client.value.send(JSON.stringify(message));
        else ws_client.value.send(message);
      }
    }
  }
  if (!messageQueue.value.isEmpty()) {
    const len = messageQueue.value.size();
    for (let i = 0; i < len; i++) {
      const msg = messageQueue.value.dequeue();
      /* check message */
      Bus.emit("update:msg", msg);
    }
  }
  if (!messageStreamQueue.value.isEmpty()) {
    const len = messageStreamQueue.value.size();
    for (let i = 0; i < len; i++) {
      const msg = messageStreamQueue.value.dequeue();
      /* check message */
      console.log("Recv Stream: ", msg);
      Bus.emit("update:stream", msg);
    }
  }
}, 100);
export default {
  url: server_url,
  host: server_host,
  connecting,
  connect,
  send: requestQueue.value.enqueue,
};
